import requests
from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__, static_url_path="/static")
botIP = '127.0.0.1'
botPort = '5005'
RASA_URL = f"http://{botIP}:{botPort}/webhooks/rest/webhook"

def request_rasa_server(content):
    params = {'message':content}
    print(RASA_URL)
    response = requests.post(RASA_URL,
                            data=json.dumps(params),
                            headers={'Content-Type':'application/json'})
    print('response1',response)
    # return response.text.encode('utf-8').decode("unicode-escape")
    return response.text


@app.route('/message', methods=['POST'])
def web_to_bot():
    question = request.form['msg']
    print('question',question)
    response = request_rasa_server(question)
    # print('response',response,'长度',len(response),type(response))
    res_msg = []
    for i in range(len(json.loads(response))):
        result = json.loads(response)[i]['text']
        res_msg.append(result)
    return jsonify({'text':res_msg})

@app.route("/")
def index():
    return render_template("index.html")


# 启动APP
if (__name__ == "__main__"):
    app.run(host='127.0.0.1', port=5000,threaded=True,debug=True)
